<template>
    <div>
      <vab-card>
        <template #header>
          <div class="flex_sb">
            <span class="leve_title">主仓明细账查询</span>
            <el-button size="small" @click="handleBack">返回</el-button>
          </div>
        </template>
        <template #default>
          <el-form
            :ref="(el: any) => (searchFormRef = el)"
            :model="searchForm"
            label-width="80px"
            label-position="left"
            class="form_search"
          >
            <el-row :gutter="24">
              <el-col
                v-for="(item, i) in _WarehouseSearch"
                :key="i"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                :xl="6"
              >
                <!-- 默认项 -->
                <el-form-item
                  v-if="item.type == 'select'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <VabSelectForm
                    :multiple="item.multiple"
                    v-if="selectOptions(item.prop)"
                    v-model.trim="searchForm[item.prop]"
                    :options="selectOptions(item.prop)"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <!-- autocomplete -->
                <el-form-item
                  v-if="item.type == 'autocomplete'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <VabAutoForm v-model="searchForm[item.prop]" :list="selectOptions(item.prop)"/>
                </el-form-item>
                <!-- input -->
                <el-form-item
                  v-if="item.type == 'input'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-input
                    clearable
                    placeholder="请输入"
                    class="width_100 height_auto"
                    v-model.trim="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <!-- time -->
                <el-form-item
                  v-if="item.type == 'time'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-date-picker
                    clearable
                    placeholder="请选择"
                    type="datetimerange"
                    class="width_100 height_auto"
                    :format="TimeFormat"
                    :default-time="DefaultTime"
                    v-model="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                :xl="6"
              >
                <div class="flex_just_end">
                  <el-button size="small" type="primary" @click="handleSearch()">
                    查询
                  </el-button>
                  <el-button size="small" @click="resetForm(searchFormRef)">
                    重置
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vab-card>
      <!-- 主 -->
      <vab-card shadow="always">
        <template #header>
          <span class="leve2_title">主仓明细账列表</span>
        </template>
        <el-table
          border
          height="520"
          style="width: 100%"
          :data="data.dataSource"
          v-loading="data.loading"
          @current-change="handleCurrentChange"
        >
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              <span
                class="ellipsis"
                v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, i) in data.cloums"
            :key="i"
            :width="item.width"
            :prop="item.prop"
            :label="item.label"
            :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'"
          >
            <template #default="scope">
              <!-- 自定义 -->
              <div v-if="item.type == 'custom'">
                <span class="ellipsis" >
                  {{ from == 'check' ? NumberFormat(scope.row.stock_num) : NumberFormat(scope.row.batch_stock_num) }}
                </span>
              </div>
              <!-- 正常 -->
              <div
                v-else
                class="ellipsis"
              >
                {{ _FieldFormat(scope.row[item.prop], item.type) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex_just_end">
          <el-pagination
            background
            small="small"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            layout="total, prev, pager, next,sizes, jumper"
            :page-sizes="[20, 50, 100, 200]"
            :pager-count="10"
            :total="data.count"
            @current-change="handlePageNum"
            @size-change="handlePageSize"
          />
        </div>
      </vab-card>
    </div>
  </template>

<script lang="ts" setup>
defineOptions({
  name: 'InventoryWarehouse',
})
/**
 * @import
 */
import {
  WarehouseSearch,
  WarehouseCloums,
  OtherOutSearchSelect,
} from './components/tools'
import { FieldFormat, DefaultTime, TimeFormat, NumberFormat, ArrayOneValue } from '~/src/utils/utils'
import { ElMessage, FormInstance, dayjs } from 'element-plus'
import { getConsignBatchChangeList, getInventoryBatchChangeList, getInventoryChangeList, getInventorySearch } from '~/src/api/dms/inventory';
/**
 * @var
 */
const route = useRoute()
const router = useRouter()
const { stock_id, from } = route.query

const otherOutDetailRef = ref<any>(null)
const isCheck = ref<Boolean>(false)
const searchFormRef = ref<any>(null)
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
})
data.dataSource = []
data.cloums = WarehouseCloums

// 筛选项
const _WarehouseSearch = ref<any>(WarehouseSearch)

// 仅寄售
if (from == 'consignSaleCheck') {
  data.cloums.forEach((el: any) => {
    if (el.label == '出入库单号') el.label = '业务单号'
  });
  _WarehouseSearch.value.forEach((el: any) => {
    if (el.label == '出入库单号') el.label = '业务单号'
  });
}



let classTwoList = ref<any>([])
/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  ElMessage({
    message: '查询成功',
    type: 'success',
  })
}
// 返回
const handleBack = () => {
  router.push(`/inventory/${from}`)
}
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = true
  await formEl.resetFields()
  await _GetProductList()
  ElMessage({
    message: '重置成功',
    type: 'success',
  })
}

// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}
// 单选
const handleCurrentChange = (row: any) => {
  otherOutDetailRef.value.requst(row.id)
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}
// 筛选项格式化
const selectOptions = (value: string) => {
  if (JSON.stringify(data.search) == '{}') return
  return OtherOutSearchSelect(data.search, value)
}
// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
// 获取数据
const _GetProductList = async () => {
  data.loading = true

  let _searchForm = { ...searchForm }
  if (!isCheck.value) _searchForm = {}

  const created_at: any = _searchForm.created_at

  const query: any = {
    page: data.pageNum,
    limit: data.pageSize,
    filter: {
      change_no: _searchForm.change_no || '', // 进出仓单号
      type_name: _searchForm.type_name || [], // 业务类型
      "created_at_start": created_at ? dayjs(created_at[0]).format(TimeFormat) : '', // 单据时间开始
      "created_at_end": created_at ? dayjs(created_at[1]).format(TimeFormat) : '', // 单据时间结束
    },
  }

  // 关键参数
  if (from == 'check') query.stock_id = stock_id
  if (from == 'detailCheck') query.stock_batch_id = stock_id
  if (from == 'consignSaleCheck') query.stock_batch_id = stock_id

  try {
    let res: any = null
    // 接口
    if (from == 'check') res = await getInventoryChangeList({ ...query })
    if (from == 'detailCheck') res = await getInventoryBatchChangeList({ ...query })
    if (from == 'consignSaleCheck') res = await getConsignBatchChangeList({ ...query })

    data.dataSource = res.data.list
    data.count = res.data.count
    data.loading = false
  } catch (error) { }
}
// 其他出入库筛选项
const _GetProductSearch = async () => {
  classTwoList.value = []
  try {
    const res = await getInventorySearch()
    res.data.out_status.unshift({ id: '', name: '全部' })
    res.data.out_order_type.unshift({ id: '', name: '全部' })

    const { type_all_name, consign_order_type } = res.data

    data.search = {
      ...res.data,
      type_all_name: from != 'consignSaleCheck' ? type_all_name : await consign_order_type.map((item: { name: any; }) => { return { name: item.name } })
    }
  } catch (error) { }
}
onMounted(() => {
  _GetProductList()
  _GetProductSearch()
})
</script>

<style lang="scss" scoped>
@import '../../components/public.scss';
</style>
